<template>
	<a-spin :spinning="isLoading">
		<draggable v-if="materialList.length > 0" class="material_list" v-model="materialList" :group="{
        name: 'controls',
        pull: 'clone',
        put: false,
      }" :sort="false" :clone="cloneControl" filter=".un-draggable" item-key="id">
			<template #item="{ element, index }">
				<div class="material_con" :style="{
            width:
              currentMaterial.id == 4 ||
              element.material_type == 'audio' ||
              element.material_type == 'text'
                ? '100%'
                : '33.3%',
          }" @dragstart="(value) => handleDragStart(value, element)"
					@dragend="(value) => handleDragEnd(value, element)"
					:class="materialList[index]?.selected ? 'un-draggable' : ''">
					<label class="cursor-pointer">
						<div class="material_item_text" v-if="element.material_type && element.material_type == 'text'"
							@click="handleCopy(element)">
							<div class="material_image">
								<cu-icon class="icon" type="icon-M_wenzi"
									style="font-size: 40px; cursor: pointer; color: #fff" />
							</div>
							<a-tooltip :title="element.material_content" autoAdjustOverflow placement="topLeft"
								color="#48484e">
								<div class="material_name">{{ element.material_content }}</div>
							</a-tooltip>
						</div>
					</label>
					<label class="cursor-pointer">
						<div class="material_item_video"
							v-if="element.material_type && element.material_type == 'image'">
							<div v-if="resourceData?.includes(element.id)" class="has-import">
								已导入
							</div>
							<div class="operate_con" :style="{ '--display': showBottomCount ? 'block' : 'none' }">
								<div class="top_check">
									<a-checkbox @change="handleCheckChange" style="margin-left: 5px"
										v-model:checked="materialList[index].checked"></a-checkbox>
								</div>
								<div class="bottom_con">
									<EyeOutlined @click.prevent="previewMaterial(element)" class="bottom_icon" />
								</div>
							</div>
							<div class="material_image" :style="{
                  border: element.checked
                    ? '1px solid #2878FF'
                    : '1px solid rgba(0, 0, 0, .8)',
                }">
								<img :src="element.material_url" alt="" />
							</div>
							<div class="material_name">{{ element.material_name }}</div>
						</div>
					</label>
					<label class="cursor-pointer">
						<div class="material_item_video" v-if="
                (element.material_type && element.material_type == 'video') ||
                (element.scene_type && element.scene_type == 'video')
              ">
							<div v-if="resourceData?.includes(element.id)" class="has-import">
								已导入
							</div>
							<div class="operate_con" :style="{ '--display': showBottomCount ? 'block' : 'none' }">
								<div class="top_check">
									<a-checkbox @change="handleCheckChange" style="margin-left: 5px"
										v-model:checked="materialList[index].checked"></a-checkbox>
								</div>
								<div class="bottom_con">
									<EyeOutlined @click.prevent="previewMaterial(element)" class="bottom_icon" />
									<template v-if="element.scene_type">
										<HeartOutlined v-if="!element.collect_count"
											@click.prevent="collectThis(element)" class="bottom_icon" />
										<HeartFilled style="color: #2878FF" @click.prevent="collectThis(element)"
											class="bottom_icon" v-else />
									</template>
								</div>
							</div>
							<div class="material_image" :style="{
                  border: element.checked
                    ? '1px solid #2878FF'
                    : '1px solid rgba(0, 0, 0, .8)',
                }">
								<div class="video_duration">
									{{ element.material_duration_text }}
								</div>
								<video :src="element.material_url" alt="" />
							</div>
							<div class="material_name">{{ element.material_name }}</div>
						</div>
					</label>
					<label class="cursor-pointer">
						<div :style="{
                border:
                  element.checked && !materialList[index]?.selected
                    ? '1px solid #2878FF'
                    : '1px solid #29292a',
              }" class="material_item_audio" v-if="
                (element.material_type && element.material_type == 'audio') ||
                (element.scene_type && element.scene_type == 'audio')
              ">
							<div class="operate_con" :style="{
                  '--display': showBottomCount ? 'flex' : 'none',
                }">
								<a-checkbox @change="handleCheckChange" class="bottom_icon"
									v-model:checked="materialList[index].checked"
									:disabled="materialList[index].selected"></a-checkbox>
								<template v-if="element.scene_type">
									<HeartOutlined v-if="!element.collect_count" @click.prevent="collectThis(element)"
										class="bottom_icon" />
									<HeartFilled style="color: #2878FF" @click.prevent="collectThis(element)"
										class="bottom_icon" v-else />
								</template>
							</div>
							<div class="left_play_icon">
								<cu-icon @click.prevent="previewMaterial(element)" class="icon" type="icon-play"
									style="font-size: 38px; cursor: pointer" />
							</div>
							<div class="right_con">
								<div class="audio_name">{{ element.material_name }}</div>
								<a-space>
									<div class="audio_duration">
										{{ element.material_duration_text }}
									</div>
									<div v-if="
									  (currentMaterial.id == 4 &&
										materialList[index]?.selected) ||
									  ((currentMaterial.id == 1 || currentMaterial.id == 2) &&
										(bgmData?.includes(element.id) ||
										  audioData?.includes(element.id)))
									" style="color: #2878FFff; font-size: 12px; font-weight: bold">
										已导入
									</div>
								</a-space>
							</div>
						</div>
					</label>
				</div>
			</template>
		</draggable>

		<div class="no_data" v-if="materialList.length == 0">暂无数据</div>

		<materialPreview :visible="previewVisible" :materialDetail="materialDetail" @close="closePreview" />
	</a-spin>
</template>

<script>
	import {
		defineComponent,
		reactive,
		toRefs,
		computed,
		watch,
		toRaw,
		createVNode,
		ref,
		nextTick,
		onMounted,
	} from "vue";
	import {
		FolderOutlined,
		PlayCircleOutlined,
		EyeOutlined,
		HeartFilled,
		HeartOutlined,
	} from "@ant-design/icons-vue";
	import draggable from "vuedraggable";
	import materialPreview from "./materialPreview.vue";
	import store from "@/store";
	import request from "../../../../../../common/utils/request";
	import {
		message
	} from "ant-design-vue";
	export default defineComponent({
		props: {
			list: {
				type: Array,
				default: () => {
					return [];
				},
			},
			currentMaterial: {
				type: Object,
				default: () => {
					return {};
				},
			},
			isLoading: {
				type: Boolean,
				default: false,
			},
			checkType: {
				type: String,
				default: "",
			},
			currentTagId: {
				type: Number,
				default: 0,
			},
			showCount: {
				type: Number,
				default: 0,
			},
		},
		components: {
			draggable,
			PlayCircleOutlined,
			EyeOutlined,
			HeartFilled,
			HeartOutlined,
			materialPreview,
		},
		setup(props, context) {
			const resourceData = computed(() => {
				const arr = [];
				store.getters.clipJSON.resource_data.forEach((i) => {
					i?.video?.forEach((item) => {
						arr.push(item.id);
					});
					i?.images?.forEach((item) => {
						arr.push(item.id);
					});
				});

				return arr;
			});
			const audioData = computed(() =>
				store.getters.clipJSON.audio.map((i) => i.id)
			);
			const bgmData = computed(() => store.getters.clipJSON.bgm.map((i) => i.id));

			const state = reactive({
				materialList: [],
				previewVisible: false,
				showBottomCount: 0,
				materialDetail: {},
			});

			watch(
				() => props?.showCount,
				(val) => {
					if (val === 0) {
						state.showBottomCount = 0;
						context.emit("showBottom", 0);
					}
				}, {
					immediate: true,
				}
			);

			watch(
				() => store.getters.clipJSON.bgm,
				(bgm) => {
					if (props.currentMaterial?.type === "popularMusic") {
						state.materialList.map((item) => {
							const findIndex = bgm.findIndex((i) => i.id == item.id);
							if (findIndex > -1) {
								item.checked = true;
								item.selected = true;
								item.disabled = true;
							} else {
								item.checked = false;
								item.selected = false;
								item.disabled = false;
							}
							return item;
						});
					}
				}, {
					deep: true,
					immediate: true,
				}
			);

			// 添加控件
			const cloneControl = (control) => {
				state.materialList.find((item) => {
					if (item.id == control.id) {
						item.checked = true;
					}
				});

				let count = 0;
				state.materialList.map((item) => {
					if (item.checked) {
						count++;
					}
				});
				state.showBottomCount = count;
				context.emit("showBottom", count);
				return control;
			};

			const previewMaterial = (element) => {
				state.previewVisible = true;
				state.materialDetail = element;
			};

			const handleCheckChange = () => {
				let count = 0;
				state.materialList.map((item) => {
					if (props.currentMaterial?.id === 4) {
						if (item.checked && item.selected !== true) {
							count++;
						}
						return;
					}
					if (item.checked) {
						count++;
					}
				});
				state.showBottomCount = count;
				context.emit("showBottom", count);
				context.emit(
					"choose",
					state.materialList.filter((i) => i.checked && i.selected !== true)
				);
			};

			const closePreview = () => {
				state.previewVisible = false;
				state.materialDetail = {};
			};

			onMounted(() => {
				state.materialList = props.list;
				state.showBottomCount = 0;
				context.emit("showBottom", 0);
				state.materialList.map((item) => {
					item.checked = false;
				});
			});

			const handleDragStart = (value, element) => {
				store.dispatch("SetDragStatus", {
					isDragging: true,
					element,
					materialList: state.materialList,
					callback: () => {
					  nextTick(() => {
					    state.materialList.map((item) => {
					      item.checked = false;
					    });
					    state.showBottomCount = 0;
					    context.emit("showBottom", 0);
					  });
					},
				})
			};

			const handleDragEnd = (value, element) => {
				store.dispatch("SetDragStatus", {
					isDragging: false,
					element,
					materialList: state.materialList,
					callback: () => {
					  nextTick(() => {
					    state.materialList.map((item) => {
					      item.checked = false;
					    });
					    state.showBottomCount = 0;
					    context.emit("showBottom", 0);
					  });
					},
				});
			};

			const collectThis = (item) => {
				console.log("props.currentTagId", props.currentTagId);
				if (!item.scene_type) return;
				let is_collect = item.collect_count ? 0 : 1;
				request
					.put("/work_ai", "/user/shotstack/material/collect", {
						material_id: item.id,
						scene_type: item.scene_type == "audio" ? "bgm" : item.scene_type,
						is_collect,
					})
					.then((res) => {
						if (item.collect_count) {
							item.collect_count = 0;
							message.success("取消收藏成功");
						} else {
							item.collect_count = 1;
							message.success("收藏成功");
						}
						if (props.currentTagId == -1) {
							context.emit("refrashMaterial", item);
						}
					});
			};

			const handleCopy = (item) => {
				navigator?.clipboard
					?.writeText(item?.material_content)
					.then(() => {
						message.success("复制成功！");
					})
					.catch(() => {
						message.error("复制失败！");
					});
			};

			watch(
				() => props.list,
				(val) => {
					state.materialList = val;
					state.showBottomCount = 0;
					context.emit("showBottom", 0);
					// state.materialList.map((item) => {
					//   item.checked = false;
					// });
				}
			);

			watch(
				() => props.checkType,
				(val) => {
					if (val) {
						if (val == "cancel") {
							state.materialList.map((item) => {
								item.checked = false;
							});
							state.showBottomCount = 0;
							context.emit("showBottom", 0);
						} else {
							let count = 0;
							state.materialList.map((item) => {
								item.checked = true;
								count++;
							});
							state.showBottomCount = count;
							context.emit("showBottom", count);
						}
					}
				}
			);

			return {
				...toRefs(state),
				resourceData,
				audioData,
				bgmData,
				cloneControl,
				previewMaterial,
				handleCheckChange,
				closePreview,
				handleDragStart,
				handleDragEnd,
				collectThis,
				handleCopy,
			};
		},
	});
</script>

<style lang="less" scoped>
	.no_data {
		color: 14px;
		width: 100%;
		height: 300px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #fff;
	}

	.material_list {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		align-items: flex-end;

		.material_con {
			.material_item_video {
				width: 83px;
				height: 113px;
				cursor: pointer;
				flex-shrink: 0;
				color: #fff;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: flex-end;
				margin-top: 10px;
				position: relative;

				.has-import {
					position: absolute;
					left: 2px;
					bottom: 30px;
					font-size: 12px;
					z-index: 3;
					color: #fff;
				}

				.operate_con {
					position: absolute;
					display: var(--display);
					left: 0;
					top: 0;
					padding: 20px;
					width: 100%;
					height: 100%;
					z-index: 99;

					.top_check {
						position: absolute;
						left: 0;
						top: 7px;
						width: 100%;
						height: 25px;
					}

					.bottom_con {
						position: absolute;
						left: 0;
						bottom: 30px;
						width: 100%;
						height: 20px;
						display: flex;
						justify-content: flex-end;
						align-items: center;

						.has-import {
							font-size: 12px;
							position: absolute;
							left: 2px;
						}

						.bottom_icon {
							margin-right: 5px;

							&:hover {
								color: #2878FF;
							}
						}
					}
				}

				&:hover {
					.operate_con {
						display: block;
					}
				}

				// 图片
				.material_image {
					display: flex;
					justify-content: center;
					align-items: center;
					width: 100%;
					height: 83px;
					background-color: rgba(0, 0, 0, 0.8);
					position: relative;
					border-radius: 8px;
					border: 1px solid rgba(0, 0, 0, 0.8);
					overflow: hidden;
					display: flex;
					align-items: center;
					justify-content: center;

					.video_duration {
						position: absolute;
						right: 3px;
						top: 0px;
						color: #fff;
					}

					video {
						height: 55%;
					}

					img {
						max-height: 83px;
						max-width: 83px;
					}
				}

				.material_name {
					margin-top: 7px;
					font-size: 12px;
					display: inline-block;
					white-space: nowrap;
					text-overflow: ellipsis;
					overflow: hidden;
					width: 80%;
					text-align: center;
				}
			}

			.material_item_text {
				display: flex;
				align-items: center;
				padding: 3px 15px;
				border-radius: 10px;
				background-color: #29292a;
				width: 100%;
				cursor: pointer;
				margin-top: 10px;
				position: relative;
				// border: 1px solid #29292a;
				color: #fff;

				.operate_con {
					display: var(--display);
					width: 100%;
					height: 100%;
					position: absolute;
					left: 0;
					top: 0;
					z-index: 99;
					padding: 20px;
					align-items: center;
					justify-content: flex-end;

					.bottom_icon {
						margin-left: 10px;
						color: #fff;
						font-size: 14px;

						&:hover {
							color: #2878FF;
						}
					}
				}

				&:hover {
					.operate_con {
						display: flex;
					}
				}

				.material_name {
					width: 200px;
					display: inline-block;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
			}

			.material_item_audio {
				display: flex;
				align-items: center;
				padding: 3px 15px;
				border-radius: 10px;
				background-color: #29292a;
				width: 100%;
				cursor: pointer;
				margin-top: 10px;
				position: relative;
				border: 1px solid #29292a;

				.operate_con {
					display: var(--display);
					width: 100%;
					height: 100%;
					position: absolute;
					left: 0;
					top: 0;
					z-index: 99;
					padding: 20px;
					align-items: center;
					justify-content: flex-end;

					.bottom_icon {
						margin-left: 10px;
						color: #fff;
						font-size: 14px;

						&:hover {
							color: #2878FF;
						}
					}
				}

				&:hover {
					.operate_con {
						display: flex;
					}
				}

				.left_play_icon {
					color: #ddd;
					font-size: 36px;
					z-index: 999;
				}

				.right_con {
					color: #ddd;
					margin-left: 10px;

					.audio_name {
						width: 170px;
						display: inline-block;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}

					.audio_duration {
						margin-top: 0px;
					}
				}
			}
		}
	}
</style>